package com.itjin.resume_back.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itjin.resume_back.dto.LoginResponse;
import com.itjin.resume_back.entity.User;
import com.itjin.resume_back.mapper.UserMapper;
import com.itjin.resume_back.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

  @Override
  public void register(User user) {
    // 检查用户名是否已存在
    if (lambdaQuery().eq(User::getUsername, user.getUsername()).exists()) {
      throw new RuntimeException("用户名已存在");
    }

    // 检查邮箱是否已存在
    if (lambdaQuery().eq(User::getEmail, user.getEmail()).exists()) {
      throw new RuntimeException("邮箱已存在");
    }

    // 密码加密
    user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
    save(user);
  }

  @Override
  public LoginResponse login(String username, String password) {
    // 查询用户
    User user = lambdaQuery()
        .eq(User::getUsername, username)
        .one();

    if (user == null) {
      throw new RuntimeException("用户不存在");
    }

    // 验证密码
    if (!user.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))) {
      throw new RuntimeException("密码错误");
    }

    // TODO: 生成JWT token
    String token = "token";

    // Important: Clear password before returning user info
    user.setPassword(null);

    // Return token and user details
    return new LoginResponse(token, user);
  }

  @Override
  public void updatePassword(Long userId, String oldPassword, String newPassword) {
    User user = getById(userId);
    if (user == null) {
      throw new RuntimeException("用户不存在");
    }

    // 验证旧密码
    if (!user.getPassword().equals(DigestUtils.md5DigestAsHex(oldPassword.getBytes()))) {
      throw new RuntimeException("原密码错误");
    }

    // 更新密码
    user.setPassword(DigestUtils.md5DigestAsHex(newPassword.getBytes()));
    updateById(user);
  }

  @Override
  public void updateStatus(Long userId, Integer status) {
    User user = getById(userId);
    if (user == null) {
      throw new RuntimeException("用户不存在");
    }

    user.setStatus(status);
    updateById(user);
  }
}